import datetime
from io import BytesIO

import xlwt


def export_excel(data, handler, name='excel'):
    workbook = xlwt.Workbook(encoding='utf-8')
    worksheet = workbook.add_sheet(name)
    if len(data) > 0:
        # 合并表头文件
        head = []
        for item in data:
            head.extend(item.keys())
        head = sorted(set(head), key=head.index)
        cell = 0
        for item in head:
            worksheet.write(0, cell, item)
            cell += 1
        # 表格体
        row = 1
        for record in data:
            cell = 0
            for key in head:
                worksheet.write(row, cell, record.get(key, "N/A"))
                cell += 1
            row += 1
    output = BytesIO()
    workbook.save(output)
    output.seek(0)
    now = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    handler.set_header("Content-Type", "application/octet-stream")
    handler.set_header("Content-Disposition", "attachment; filename=%s-%s.xlsx" % (name, now))
    return handler.write(output.getvalue())
